package sd_services

import (
	"fmt"
	"log"
	"xiehui-service/app/models/sd_models"
	"xiehui-service/global"

	"go.uber.org/zap"
)

type materialService struct {
}

var MaterialService = new(materialService)

// 查询原材料信息
func (materialService *materialService) MaterialList(stamp float64, num int64) (materials []sd_models.Material, err error) {
	err = global.App.MSACCESS.Ping()
	if err != nil {
		log.Println("ping==>>", err)
		global.App.Log.Error("查询原材料数据失败：", zap.Any("数据库联接", "ping失败"))
		return nil, err
	}
	rows, err := global.App.MSACCESS.Query(fmt.Sprintf("select Top %d * from Material where Stamp > %.10f order by Stamp asc", num, stamp))
	if err != nil {
		log.Println("query==>>", err)
		global.App.Log.Error("查询原材料数据失败：", zap.Any("Query查询失败", err))
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var materialItem sd_models.Material
		if err := rows.Scan(&materialItem.ID, &materialItem.Name, &materialItem.Specs, &materialItem.Flag, &materialItem.Notes, &materialItem.Stamp, &materialItem.MinValue, &materialItem.MixValue); err != nil {
			log.Println("scan==>>", err)
		}
		materials = append(materials, materialItem)
	}

	if err := rows.Err(); err != nil {
		log.Println("rows.err==>>", err)
		global.App.Log.Error("查询原材料数据失败：", zap.Any("查询失败", err))
		return nil, err
	}

	return materials, nil
}

func (materialService *materialService) GetMaterialSpecById(id string) (spec *string, err error) {
	err = global.App.MSACCESS.Ping()
	if err != nil {
		log.Println("ping==>>", err)
		global.App.Log.Error("查询原材料数据失败：", zap.Any("数据库联接", "ping失败"))
		return nil, err
	}

	row := global.App.MSACCESS.QueryRow("select Specs from Material where ID = ? order by Stamp asc", id)

	if err := row.Scan(&spec); err != nil {
		log.Println("GetMaterialById scan==>>", err)
	}

	return spec, nil
}

// 根据资源ID获取资源
func (materialService *materialService) GetMaterialById(id string) (m *sd_models.Material, err error) {
	err = global.App.MSACCESS.Ping()
	if err != nil {
		log.Println("ping==>>", err)
		global.App.Log.Error("查询原材料数据失败：", zap.Any("数据库联接", "ping失败"))
		return nil, err
	}

	sql := "select Top 1 * from Material where ID = ?"
	row := global.App.MSACCESS.QueryRow(sql, id)

	var material sd_models.Material
	if err := row.Scan(&material.ID, &material.Name, &material.Specs, &material.Flag, &material.Notes, &material.Stamp, &material.MinValue, &material.MixValue); err != nil {
		log.Println("GetMaterialById scan==>>", err)
	}

	return &material, nil
}
